﻿using Newtonsoft.Json;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace Emoticon_Tools_Fw
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private ObservableCollection<emoticon> emoticons = new ObservableCollection<emoticon>();
        private string selectedEmoticonUrl = string.Empty;
        private int pageIndex = 0;

        public class emoticon
        {
            public string id { get; set; }

            public int height { get; set; }

            public int width { get; set; }

            public string path { get; set; }

            public string imgUrl
            {
                get { return path == null ? null : "http://image.dbbqb.com/" + path; }
                set { path = value == null ? null : value; }
            }
        }
        public MainWindow()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 获取表情图
        /// </summary>
        /// <returns></returns>
        void getEmoticons()
        {
            string url = $"http://www.dbbqb.com/api/search/json?start={pageIndex}&size=96";
            string text = SearchText.Text;

            if (!string.IsNullOrWhiteSpace(text))
            {
                url = url + "&w=" + text;
            }

            string result = null;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.TryParseAdd("application/json");
                client.DefaultRequestHeaders.AcceptLanguage.TryParseAdd("zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6");
                client.DefaultRequestHeaders.UserAgent.TryParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 Edg/100.0.1185.50");

                client.DefaultRequestHeaders.Add("Method", "GET");
                client.DefaultRequestHeaders.Add("Web-Agent", "web");
                client.DefaultRequestHeaders.Add("Cookie", "Hm_lvt_7d2469592a25c577fe82de8e71a5ae60=1650630029,1650632573,1650762170,1650771418; Hm_lpvt_7d2469592a25c577fe82de8e71a5ae60=1650771423");

                HttpResponseMessage res = client.GetAsync(url).Result;

                if (res.StatusCode == HttpStatusCode.OK)
                {
                    result = res.Content.ReadAsStringAsync().Result;
                }
            }

            if (result != null)
            {
                var list = JsonConvert.DeserializeObject<ObservableCollection<emoticon>>(result);

                foreach (var item in list)
                {
                    emoticons.Add(item);
                }

                List.DataContext = emoticons;
            }
        }

        /// <summary>
        /// 复制表情包
        /// </summary>
        void copyEmoticons()
        {
            if (string.IsNullOrWhiteSpace(selectedEmoticonUrl))
            {
                return;
            }

            Uri uri = new Uri(selectedEmoticonUrl);

            MemoryStream outStream = new MemoryStream();
            PngBitmapEncoder encoder = new PngBitmapEncoder();
            encoder.Interlace = PngInterlaceOption.Off;
            encoder.Frames.Add(BitmapFrame.Create(uri));

            //可以内存流改为文件流，将生成Png格式的图片文件
            encoder.Save(outStream);

            // Create source.
            BitmapImage bitImg = new BitmapImage();
            // BitmapImage.UriSource must be in a BeginInit/EndInit block.
            bitImg.BeginInit();
            bitImg.StreamSource = outStream;
            bitImg.EndInit();

            if (Clipboard.ContainsImage())
            {
                Clipboard.SetImage(bitImg);
            }

            Clipboard.SetImage(bitImg);
        }

        //搜索
        private void btn_Click(object sender, RoutedEventArgs e)
        {
            pageIndex = 0;
            emoticons.Clear();
            getEmoticons();
        }

        //复制
        private void copy_Click(object sender, RoutedEventArgs e)
        {
            copyEmoticons();
        }

        //选中
        private void SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            emoticon item = List.SelectedItem as emoticon;

            if (item != null && item is emoticon)
            {
                //MessageBox.Show("当前选中图片地址为：" + item.imgUrl);
                selectedEmoticonUrl = item.imgUrl;
            }
        }

        //监听滚动条到底部
        private void Scroll_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            // Get the border of the listview (first child of a listview)
            Decorator border = VisualTreeHelper.GetChild(sender as ListView, 0) as Decorator;
            // Get scrollviewer
            ScrollViewer scrollViewer = border.Child as ScrollViewer;
            if (scrollViewer.VerticalOffset == scrollViewer.ScrollableHeight)
            {
                getEmoticons();
                pageIndex++;
            }
        }
    }
}
